<!-- 产品碳足迹-碳足迹看板 -->

<template>
  <div>
    <div class="m_contentBox">
      <a-card :bordered="false">
        <div class="m_aCardBox">
          <!-- 选择产品筛选 -->
          <div class="tabBox">
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="24">
                  <a-col :span="6">
                    <a-form-model-item :label="$t('message.Select_products')">
                      <a-select v-model="queryParam.productId" :placeholder="$t('message.Please_enter')" show-search
                                :filter-option="filterOption" @change="onChangeNumeratorUnitId" style="width: 100%;">
                        <a-select-option :value="item.id" v-for="(item,index) in productData" :key="index">
                          {{ item.productName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="6">
                  </a-col>
                  <a-col :span="6">
                  </a-col>
                  <a-col :span="6">
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </div>
          <!-- 统计部分 -->
          <a-spin :spinning="loading">
            <section class="statisticsBox" v-if="queryParam.productId">
              <section class="statisticsBox_box1">
                <div class="statisticsBox_box1_item">
                  <div class="statisticsBox_box1_item_label">
                    {{$t('message.Accounting_has_been_created')}}（{{ $t('message.single') }}）
                  </div>
                  <div class="statisticsBox_box1_item_text" style="color: #2c57ff;">
                    {{ dataSource.accountingTotal || "0" }}
                  </div>
                </div>
                <div class="statisticsBox_box1_item">
                  <div class="statisticsBox_box1_item_label">
                    {{$t('message.Model_creation')}}（{{ $t('message.single') }}）
                  </div>
                  <div class="statisticsBox_box1_item_text" style="color: #148958;">
                    {{ dataSource.modelTotal || "0" }}
                  </div>
                </div>
                <div class="statisticsBox_box1_item">
                  <div class="statisticsBox_box1_item_label">
                    {{$t('message.Accounting_completion')}}（{{ $t('message.single') }}）
                  </div>
                  <div class="statisticsBox_box1_item_text" style="color: #E37318;">
                    {{ dataSource.completeTotal || "0" }}
                  </div>
                </div>
                <div class="statisticsBox_box1_item">
                  <div class="statisticsBox_box1_item_label">
                    {{$t('message.Archived')}}（{{ $t('message.single') }}）
                  </div>
                  <div class="statisticsBox_box1_item_text" style="color: #333333;">
                    {{ dataSource.archivedTotal || "0" }}
                  </div>
                </div>
              </section>
              <div class="statisticsBox_hr">
              </div>
              <div class="statisticsBox_dateRange">
                <div class="statisticsBox_dateRange_text1">{{ $t('message.Latest_accounting_cycle') }}：
                </div>
                <div class="statisticsBox_dateRange_text2">
                  {{ dataSource.beginTime ? dataSource.beginTime.slice(0, 10) : '' }}
                  {{ $t('message.to') }}
                  {{ dataSource.endTime ? dataSource.endTime.slice(0, 10) : '' }}
                </div>
                <div class="statisticsBox_dateRange_text3 m_hoverCP" @click="onViewMore">
                  {{ $t('message.View_more') }}
                </div>
              </div>
              <section class="statisticsBox_box2">
                <div class="statisticsBox_box2_item">
                  <div class="statisticsBox_box2_item_label">{{ $t('message.Life_cycle_boundary') }}
                  </div>
                  <div class="statisticsBox_box2_item_text" v-if="dataSource.lifeCycleType == 1">
                    {{ $t('message.From_cradle_to_gate') }}
                  </div>
                  <div class="statisticsBox_box2_item_text" v-else-if="dataSource.lifeCycleType == 2">
                    {{ $t('message.From_cradle_to_grave') }}
                  </div>
                  <div class="statisticsBox_box2_item_text" v-else-if="dataSource.lifeCycleType == 3">
                    {{ $t('message.Customize') }}
                  </div>
                  <div class="statisticsBox_box2_item_text" v-else> -</div>
                </div>
                <div class="statisticsBox_box2_item">
                  <div class="statisticsBox_box2_item_label">
                    {{ $t('message.Product_carbon_footprint') }}（kg CO₂e）
                  </div>
                  <div class="statisticsBox_box2_item_text">{{ dataSource.cptzjValue || "-" }}
                  </div>
                </div>
                <div class="statisticsBox_box2_item">
                  <div class="statisticsBox_box2_item_label">
                    {{ $t('message.Maximum_emission_stage') }}：{{ dataSource.zdpfljdName || "-" }}（kg CO₂e）
                  </div>
                  <div class="statisticsBox_box2_item_text">{{ dataSource.zdpfljdValue || "-" }}
                  </div>
                </div>
                <div class="statisticsBox_box2_item">
                  <div class="statisticsBox_box2_item_label">
                    {{ $t('message.Maximum_emission_type') }}：{{ dataSource.zdpfllxName || "-" }}（kg CO₂e）
                  </div>
                  <div class="statisticsBox_box2_item_text">
                    {{ dataSource.zdpfllxValue || "-" }}
                  </div>
                </div>
              </section>
              <section class="statisticsBox_tab">
                <a-tabs :activeKey="activeKey" @change="onChangeActiveKey">
                  <a-tab-pane key="1" :tab="`${$t('message.Emission_rank')}（${$t('message.Emission_inventory')}）`" forceRender>
                    <div class="tabInnerBox">
                      <div class="chart1" id="chart_bar_pfqd"></div>
                    </div>
                  </a-tab-pane>
                  <a-tab-pane key="2" :tab="`${$t('message.Emission_rank')}（${$t('message.Stage')}）`" forceRender>
                    <div class="tabInnerBox">
                      <div class="chartBox">
                        <div class="chart2" id="chart_bar_jd"></div>
                        <div class="chart3" id="chart_pie_jd"></div>
                      </div>
                    </div>
                  </a-tab-pane>
                  <a-tab-pane key="3" :tab="`${$t('message.Emission_rank')}（${$t('message.Working_procedure')}）`" forceRender>
                    <div class="tabInnerBox">
                      <div class="chartBox">
                        <div class="chart2" id="chart_bar_gx"></div>
                        <div class="chart3" id="chart_pie_gx"></div>
                      </div>
                    </div>
                  </a-tab-pane>
                </a-tabs>
              </section>
            </section>


          </a-spin>
        </div>
      </a-card>
    </div>
  </div>

</template>

<script>
import * as echarts from 'echarts'
import {getAction} from '@/api/manage'
import {commonBarChartOption} from "@/common/constKey";
import {
  set_TPYZ_ProductId,
} from "@/common/storage";

export default {
  name: 'footprintHomeView',
  data() {
    return {
      activeKey: '1', // 1排放量排行（排放清单）/ 2排放量排行（阶段）/ 3排放量排行（工序）
      queryParam: {},// 查询请求数据
      productData: [], // 产品数据
      dataSource: {}, //
      loading: false,
    };
  },
  created() {
    this.getData()
  },
  methods: {
    /**
     * 查看更多
     */
    onViewMore() {
      set_TPYZ_ProductId(this.queryParam.productId)
      this.$router.push(`/module_footprint/footprintProductView/footprintProductView`)
    },
    /**
     * 切换tab
     * @param key 1排放量排行（排放清单）/ 2排放量排行（阶段）/ 3排放量排行（工序）
     */
    onChangeActiveKey(key) {
      console.log('onChangeActiveKey', key);
      this.activeKey = key
    },
    /**
     * 修改产品
     */
    onChangeNumeratorUnitId(value) {
      console.log('onChangeNumeratorUnitId', value)
      // 获取数据
      this.dataSource = {}
      this.loading = true
      getAction('/footprintProduct/cyFootprintProduct/getViewData', {
        productId: this.queryParam.productId
      }).then((res) => {
        if (res.success) {
          let resData = res.result || {}
          let theIndex = this.productData.findIndex(ele => ele.id == value)
          if (theIndex > -1) {
            let obj = this.productData[theIndex]
            resData.accountingTotal = obj.accountingTotal
            resData.modelTotal = obj.modelTotal
            resData.completeTotal = obj.completeTotal
            resData.archivedTotal = obj.archivedTotal
          }
          let cptzjValue = 0
          resData.zdpfljdValue = 0
          resData.zdpfllxValue = 0
          if (resData.detailList && resData.detailList.length > 0) {
            resData.detailList.forEach(item => {
              cptzjValue = cptzjValue + item.total
              if (item.total > resData.zdpfljdValue) {
                resData.zdpfljdName = item.name
                resData.zdpfljdValue = item.total
              }
              item.childList.forEach(itemA => {
                itemA.detailList.forEach(itemB => {
                  if (itemB.emissionsVolume > resData.zdpfllxValue) {
                    resData.zdpfllxName = itemB.type
                    resData.zdpfllxValue = itemB.emissionsVolume
                  }
                })
              })
            })
          }
          resData.cptzjValue = cptzjValue
          if (resData.emissionRanking && resData.emissionRanking.length > 0) {
            resData.emissionRanking.forEach(item => {
              if (item.typeName == '按清单') {
                this.drawLine1(item.listKey, item.listValue)
              }
              if (item.typeName == '按环节') {
                this.drawLine2(item.listKey, item.listValue)
                this.drawLine3(this.computePieData(item))
              }
              if (item.typeName == '按工序') {
                this.drawLine4(item.listKey, item.listValue)
                this.drawLine5(this.computePieData(item))
              }
            })
          }
          this.dataSource = resData
        }
      }).finally(() => {
        this.loading = false
      });
    },
    /**
     * 处理饼图数据
     */
    computePieData(item) {
      // 总数
      let totalNum = 0
      item.listValue.forEach(item => {
        totalNum = totalNum + item
      })
      // 拼接数据
      let valueData = []
      item.listKey.forEach((itemA, indexA) => {
        valueData.push({
          name: itemA,
          value: item.listValue[indexA],
          proportion: totalNum === 0 ? 0 : Number(((item.listValue[indexA] / totalNum) * 100).toFixed(2))
        })
      })
      console.log('valueData', valueData)
      return valueData
    },
    /**
     * 排放量排行（排放清单）【柱状图】
     */
    drawLine1(labelData, valueData) {
      console.log('drawLine1')
      let chart_bar_pfqd = echarts.init(
          document.getElementById('chart_bar_pfqd')
      )
      let option = commonBarChartOption('#148958', labelData, valueData)
      //使用制定的配置项和数据显示图表
      chart_bar_pfqd.setOption(option)
    },
    /**
     * 排放量排行（阶段）【柱状图】
     */
    drawLine2(labelData, valueData) {
      console.log('drawLine2')
      let chart_bar_jd = echarts.init(
          document.getElementById('chart_bar_jd')
      )
      let option = commonBarChartOption('#F99550', labelData, valueData)
      //使用制定的配置项和数据显示图表
      chart_bar_jd.setOption(option)
    },
    /**
     * 排放量排行（阶段）【饼图】
     */
    drawLine3(valueData) {
      console.log('drawLine3')
      let chart_pie_jd = echarts.init(
          document.getElementById('chart_pie_jd')
      )
      let option = this.commonPieOption(valueData)
      //使用制定的配置项和数据显示图表
      chart_pie_jd.setOption(option)
    },
    /**
     * 排放量排行（工序）【柱状图】
     */
    drawLine4(labelData, valueData) {
      console.log('drawLine2')
      let chart_bar_gx = echarts.init(
          document.getElementById('chart_bar_gx')
      )
      let option = commonBarChartOption('#F99550', labelData, valueData)
      //使用制定的配置项和数据显示图表
      chart_bar_gx.setOption(option)
    },
    /**
     * 排放量排行（工序）【饼图】
     */
    drawLine5(valueData) {
      console.log('drawLine5')
      let chart_pie_gx = echarts.init(
          document.getElementById('chart_pie_gx')
      )
      let option = this.commonPieOption(valueData)
      //使用制定的配置项和数据显示图表
      chart_pie_gx.setOption(option)
    },
    /**
     * 饼图配置
     */
    commonPieOption(valueData) {
      return {
        color: ['#1BC08A', '#81E0DB', '#FFC439', '#FF8C73', '#F35571'],
        legend: {
          show: true,
          icon: 'circle',
          type: 'plain',
          left: '60%',
          top: 'middle',
          formatter: function (name) {
            let proportion
            let value;
            valueData.forEach(item => {
              if (item.name === name) {
                proportion = item.proportion
                value = item.value
              }
            })
            return `{name|${name}}{proportion|${proportion}%}{value|${value}}`
          },
          textStyle: {
            rich: {
              name: {
                // 碳排名称
                fontSize: 16,
                fontWeight: 400,
                width: 100,
                color: '#777777',
                fontFamily: 'PingFang SC',
              },
              proportion: {
                // 碳排量占比
                fontSize: 14,
                fontWeight: 400,
                width: 70,
                color: '#2B7450',
                fontFamily: 'PingFang SC',
              },
              value: {
                // 碳排量
                fontSize: 14,
                fontWeight: 400,
                width: 100,
                color: '#2B7450',
                fontFamily: 'PingFang SC',
              }
            }
          },
        },
        series: [{
          type: 'pie',
          center: ['30%', '50%'], //饼图位置
          radius: ['50%', '80%'],
          avoidLabelOverlap: false,
          label: {
            normal: {
              show: false,
              position: 'center', //文字显示在中间
              align: 'center',
              verticalAlign: 'middle',
              textStyle: {
                //设置文字样式
                fontSize: '0'
              }
            },
            emphasis: {
              show: true, //文字至于中间时，这里需为true
              textStyle: {
                //设置文字样式
                fontSize: '14',
                color: 'rgba(145,213,255,0.85)'
              },
              formatter: function ({data}) {
                return `{value| ${data.value || '0'}}{valueUnit| kgCO₂e } \n {proportion| ${data.proportion || '0'}}{proportion| % } \n {name|${data.name}}`
              },
              //样式设置
              rich: {
                value: {
                  // 碳排量
                  lineHeight: 36,
                  fontSize: 24,
                  fontWeight: 600,
                  color: '#2B3674',
                },
                valueUnit: {
                  // 碳排量单位
                  fontSize: 14,
                  fontWeight: 600,
                  color: '#2B3674',
                },
                proportion: {
                  // 碳排量占比
                  lineHeight: 27,
                  fontSize: 18,
                  fontWeight: 500,
                  color: '#2B3674',
                },
                name: {
                  // 碳排名称
                  lineHeight: 24,
                  fontSize: 16,
                  fontWeight: 400,
                  color: '#777777',
                }
              }
            }
          },
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 5
          },
          labelLine: {
            show: false
          },
          data: valueData
        }]
      }
    },
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    getData() {
      // 产品
      getAction('/footprintProduct/cyFootprintProduct/getProductListByTime').then((res) => {
        if (res.success) {
          this.productData = res.result || []
          if (res.result) {
            this.queryParam.productId = res.result[0].id
            this.onChangeNumeratorUnitId(res.result[0].id)
          }
        }
      });
    },
  },
};

</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  background: #F5F8F7;
}

.tabBox {
  padding: 24px 24px 0;
  background: #FFFFFF;
  border-radius: 3px;
}


.selectProductBox {
  display: flex;
  align-items: center;
  padding: 0 24px;
  width: 100%;
  height: 66px;
  background: #FFFFFF;
  border-radius: 3px;

  .selectProductBox_label {
    margin-right: 10px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.9);
  }

  .selectProductBox_content {
    width: 230px;
  }
}

.tabInnerBox {
  //padding: 8px 24px 0;
}


.statisticsBox {
  box-sizing: border-box;
  margin-top: 24px;
  padding: 24px;
  width: 100%;
  background: #FFFFFF;
  border-radius: 3px;

  .statisticsBox_box1 {
    padding: 0 253px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .statisticsBox_box1_item {

  }

  .statisticsBox_box1_item_label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }

  .statisticsBox_box1_item_text {
    margin-top: 20px;
    font-family: DIN_MEDIUM;
    font-weight: 500;
    font-size: 38px;
    color: #148958;
  }

  .statisticsBox_hr {
    margin-top: 24px;
    width: 100%;
    height: 1px;
    background: #E7E7E7;
  }

  .statisticsBox_dateRange {
    margin-top: 24px;
    display: flex;
    align-items: center;
  }

  .statisticsBox_dateRange_text1 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #888888;
  }

  .statisticsBox_dateRange_text2 {
    margin-left: 14px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
  }

  .statisticsBox_dateRange_text3 {
    margin-left: 14px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #148958;
  }

  .statisticsBox_box2 {
    box-sizing: border-box;
    margin-top: 24px;
    padding: 0 119px;
    width: 100%;
    height: 145px;
    background: #FBFBFB;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .statisticsBox_box2_item {

  }

  .statisticsBox_box2_item_label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #888888;
  }

  .statisticsBox_box2_item_text {
    margin-top: 24px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
  }

  .statisticsBox_tab {
    margin-top: 24px;
    width: 100%;

  }
}

.chart1 {
  width: 100%;
  height: 400px;
  //border: 1px solid red;
}

.chartBox {
  display: flex;
  justify-content: space-between;
}

.chart2 {
  flex: 1;
  height: 400px;
  //border: 1px solid red;
}

.chart3 {
  flex: 1;
  height: 400px;
  //border: 1px solid red;
}

#chart_bar_pfqd {

}

#chart_bar_jd {

}

#chart_pie_jd {

}

#chart_bar_gx {

}

#chart_pie_gx {

}

</style>
